package com.learn.code.juc.thread;

import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author : 翌擎科技
 * @date : 2022/8/5 10:57
 */

@Component
public class LearnCodeTaskExecutor implements AsyncTaskExecutor {
    /**
     * 核心线程数
     */
    private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() + 1;
    /**
     * 最大线程数
     */
    private static final int MAX_POOL_SIZE = (Runtime.getRuntime().availableProcessors() + 1) << 1;
    /**
     * 当线程数大于核心时，这是多余的空闲线程在终止前等待新任务的最长时间。
     */
    private static final long KEEP_ALIVE_TIME = 60;

    /**
     * 队列数
     */
    private static final int QUEUE_CAPACITY = 5000;

    private final ThreadPoolExecutor threadPoolExecutor;

    public LearnCodeTaskExecutor() {
        /**
         * 定义线程池
         */
        ThreadFactory threadFactory = new CustomizableThreadFactory("learn_code_pool_");

        this.threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(QUEUE_CAPACITY),
                threadFactory,
                new ThreadPoolExecutor.AbortPolicy());
    }


    @Override
    public void execute(@Nonnull Runnable task, long startTimeout) {
        this.execute(task);
    }

    @Override
    public Future<?> submit(@Nonnull Runnable task) {
        return this.threadPoolExecutor.submit(task);
    }

    @Override
    public <T> Future<T> submit(@Nonnull Callable<T> task) {
        return this.threadPoolExecutor.submit(task);
    }

    @Override
    public void execute(@Nonnull Runnable task) {
        this.threadPoolExecutor.execute(task);
    }

    /**
     * 关闭线程池，等待任务都执行完
     *
     * @return
     */
    public void shutdown() {
        this.threadPoolExecutor.shutdown();
    }

    /**
     * 关闭线程池，不等待任务执行完
     *
     * @return
     */
    public List<Runnable> shutdownNow() {
        return this.threadPoolExecutor.shutdownNow();
    }

    /**
     * 线程池已执行和未执行的任务总数
     *
     * @return
     */
    public long getTaskCount() {
        return this.threadPoolExecutor.getTaskCount();
    }

    /**
     * 已完成的任务数量
     *
     * @return
     */
    public long getCompleteTaskCount() {
        return this.threadPoolExecutor.getCompletedTaskCount();
    }

    /**
     * 线程池当前的线程数量
     *
     * @return
     */
    public long getPoolSize() {
        return this.threadPoolExecutor.getPoolSize();
    }

    /**
     * 当前线程池中正在执行任务的线程数量
     *
     * @return
     */
    public long getActiveCount() {
        return this.threadPoolExecutor.getActiveCount();
    }
}
